<template>
	<a-modal v-bind="options" class="dic-edit-dialog">
		<a-form ref="form" :model="dic" layout="vertical">
			<a-form-item label="名称" name="name" :rules="[{required: true, message: '请输入名称'}]">
				<a-input v-model:value="dic.name" :maxlength="10" show-count placeholder="请输入名称" />
			</a-form-item>
			<a-form-item v-if="showIconUpload" label="图标" name="iconUrl">
				<file-upload v-model:file="icon" :multiple="false" accept=".jpg,.png,.jpeg" />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script lang="ts" setup>
	import {computed, reactive, ref, toRef, watchEffect} from 'vue'
	import {Dic, Img} from 'yuxin-base/src/types'
	import {FormInstance, message} from 'ant-design-vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import FileUpload from '@/components/common/file-upload.vue'

	const props = defineProps<{
		value?: Dic
		visible: boolean
	}>()

	const icon = ref<Img>({})
	const dic = ref<Dic>({})
	const form = ref<FormInstance>()

	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		confirmLoading: false,
		title: computed(() => dic.value.title || '编辑'),
		visible: toRef(props, 'visible'),
		onOk() {
			submit()
		},
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const showIconUpload = computed(() => {
		return ['HOUSE@OUTFIT', 'HOUSE@PUBAREACONFIG'].includes(dic.value.label as string)
	})

	const submit = () => {
		form.value?.validate().then(() => {
			options.confirmLoading = true

			dic.value.iconUrl = icon.value.url
			settingApi[dic.value.id ? 'updateDic' : 'insertDic'](dic.value)
				.then(() => {
					options.onCancel()
					message.success('保存成功')
				})
				.finally(() => (options.confirmLoading = false))
		})
	}

	watchEffect(() => {
		if (props.visible) {
			dic.value = props.value || {}
			if (dic.value.id) {
				settingApi.getDicById(dic.value.id).then(({data}) => {
					Object.assign(dic.value, data)
					icon.value = {url: data.iconUrl}
				})
			}
		} else {
			icon.value = {}
			form.value?.resetFields()
		}
	})
</script>

<style lang="less" scoped></style>
